package ua.diploma.login;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import ua.diploma.core.Constants;
import ua.diploma.core.ServiseFactory;
import ua.diploma.hibernate.dto.User;
import ua.diploma.user.UserBean;
import static ua.diploma.core.Constants.MIN_LOGIN_LENGHT;
import static ua.diploma.core.Constants.MIN_PASS_LENGHT;
import static ua.diploma.core.Constants.VALIDATION_ERROR_LOGIN_LENGTH;
import static ua.diploma.core.Constants.VALIDATION_ERROR_PASSWORD_LENGTH;
import static ua.diploma.core.Constants.USER_BEAN_ATTRIBUTE;

/**
 * Контроллер занимаеться запросами на аутентификацию и прекращение сессии
 * 
 * @author netstalk3r
 */
@WebServlet(name = "login", urlPatterns = { "/private/login" })
public class LoginController extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/**
	 * логгер
	 */
	private static final Logger log = Logger.getLogger(LoginController.class);

	/**
	 * Конструктор по умолчанию
	 */
	public LoginController() {
		super();
	}

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		final String action = request.getParameter(Constants.ACTION_PARAM);

		if (action == null) {
			request.getRequestDispatcher(Constants.LOGIN_VIEW).forward(request,
					response);
			log.info("action = " + action + " ---> Перенаправление");
			return;
		} else if (action.equals("login")) {
			log.info("action = " + action + " ---> Авторизация");
			final String username = request.getParameter("login");
			final String password = request.getParameter("pass");

			String redirectURL = "/webchat/";
			Boolean isValid = false;

			ArrayList<String> validationErrors = validate(username, password);
			if (validationErrors.size() == 0) {
				try {
					User user = ServiseFactory.getLoginServise().logIn(
							username, password);
					UserBean userBean = new UserBean();
					userBean.setId(user.getId());
					userBean.setLogin(user.getLogin());
					userBean.setAuthorised(true);
					request.getSession().removeAttribute(USER_BEAN_ATTRIBUTE);
					log.info(userBean);
					request.getSession().setAttribute(USER_BEAN_ATTRIBUTE, userBean);
				} catch (AuthenticationException e) {
					validationErrors.add(e.getMessage());
				}
				if (validationErrors.size() == 0) {
					isValid = true;
				}
			}
			log.info("redirectURL = " + redirectURL + " isValid = " + isValid + " validationErrors = " + validationErrors);
			request.setAttribute("redirectURL", redirectURL);
			request.setAttribute("isValid", isValid);
			request.setAttribute("errors", validationErrors);
			request.getRequestDispatcher(Constants.VALID_JSON_LOGIN_VIEW).forward(
					request, response);
			return;
		} else if (action.equals("logout")) {
			log.info("action = " + action + " ---> Выход из чата");
			request.getSession().invalidate();
			response.sendRedirect("/webchat");
			
		}
	}

	private ArrayList<String> validate(String userName, String password) {
		ArrayList<String> validationErrors = new ArrayList<String>();
		if (userName == null || userName.length() < MIN_LOGIN_LENGHT) {
			validationErrors.add(VALIDATION_ERROR_LOGIN_LENGTH);
		}
		if (password == null || password.length() < MIN_PASS_LENGHT) {
			validationErrors.add(VALIDATION_ERROR_PASSWORD_LENGTH);
		}
		return validationErrors;
	}
}
